package com.ruis.kotboot.config.confs

import com.alibaba.druid.pool.DruidDataSource
import com.alibaba.druid.support.http.StatViewServlet
import com.alibaba.druid.support.http.WebStatFilter
import com.baomidou.mybatisplus.plugins.PaginationInterceptor
import com.ruis.kotboot.common.core.BeanNames
import org.mybatis.spring.annotation.MapperScan
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.web.servlet.FilterRegistrationBean
import org.springframework.boot.web.servlet.ServletRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import javax.servlet.Filter
import javax.servlet.http.HttpServlet
import javax.sql.DataSource

@Configuration
@MapperScan(basePackages = ["com.ruis.kotboot.api"])
class DruidConfig {

    /**
     * 分页插件
     */
    @Bean
    fun paginationInterceptor(): PaginationInterceptor {
        return PaginationInterceptor()
    }

    @Bean(BeanNames.DB_SYS)
    @ConfigurationProperties(prefix = "druid.datasource")
    fun druidDataSource(): DataSource {
        return DruidDataSource()
    }

//    @Bean
//    @ConfigurationProperties(prefix = "mybatis-plus")
//    fun sqlSessionFactory(@Qualifier(BeanNames.DB_SYS)sysdb:DataSource): MybatisSqlSessionFactoryBean {
//        return MybatisSqlSessionFactoryBean().also {
//            it.setDataSource(sysdb)
//        }
//    }
}


/*-----------------配置druid显示界面 */
@Configuration
@ConfigurationProperties(prefix = "druid.view")
@ConditionalOnProperty(prefix = "druid.view", name = ["enable"], havingValue = "true")
class DruidViewConfig{
    var username:String?=null
    var password:String?=null
    var slowsql:String?=null

    @Bean
    fun druidServlet(): ServletRegistrationBean<HttpServlet> {
//        if(!enable!!)return throw Exception()
        val reg = ServletRegistrationBean<HttpServlet>()
        reg.servlet=StatViewServlet()
        reg.addUrlMappings("/druid/*")
        reg.addInitParameter("loginUsername", username)
        reg.addInitParameter("loginPassword", password)
        reg.addInitParameter("logSlowSql", slowsql)
        return reg
    }

    @Bean
    fun filterRegistrationBean(): FilterRegistrationBean<Filter> {
//        if(!enable!!)return throw Exception()
        val filterRegistrationBean = FilterRegistrationBean<Filter>()
        filterRegistrationBean.filter = WebStatFilter()
        filterRegistrationBean.addUrlPatterns("/*")
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*")
        filterRegistrationBean.addInitParameter("profileEnable", "true")
        return filterRegistrationBean
    }
}